import requests
import math
import pandas as pd
from datetime import datetime
from to_QQemail import goto_email
from get_up_xh import get_near_xh
from time import sleep

# 读取数据
jj_my = pd.read_excel(r'../Fund_form_files/jj_bd.xlsx', dtype={'基金代码': str, '基金名称': str})
jj_rc = pd.read_excel(r'../Fund_form_files/JJ_all.xlsx', dtype={'基金代码': str, '基金名称': str, '板块': str})
list_jz = []
list_time = []
gz = []
gzf = []
gz_time = []
now_date = datetime.now().strftime('%m月%d日')


def get_fund_data(fund_code, page_count=1):
    for page in range(1, page_count + 1):
        url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex={page}&pageSize=20"
        headers = {'Referer': 'http://fundf10.eastmoney.com', 'User-Agent': 'Mozilla/5.0'}
        try:
            r = requests.get(url, headers=headers, timeout=10)
            data = r.json()['Data']['LSJZList']
            for item in data:
                list_jz.append(float(item['DWJZ']))
                list_time.append(item['FSRQ'])
        except Exception as e:
            print(f"基金 {fund_code} 历史数据获取失败: {e}")
    try:
        gz_url = f"http://fundgz.1234567.com.cn/js/{fund_code}.js"
        gz_response = requests.get(gz_url, timeout=10)
        gz_data = gz_response.text
        gz.append(float(gz_data.split('gsz":"')[1].split('","')[0]))
        gzf.append(float(gz_data.split('gszzl":"')[1].split('","')[0]))  # 估算涨幅
        gz_time.append(gz_data.split('gztime":"')[1].split('"});')[0])
    except Exception as e:
        print(f"基金 {fund_code} 当日估值获取失败: {e}")


def init_all():
    gz.clear()
    gzf.clear()
    list_jz.clear()
    list_time.clear()
    gz_time.clear()


def to_cy():
    jj_code = jj_rc['基金代码'].values
    jj_name = jj_rc['基金名称'].values
    with open(f'分析log/{now_date}持仓分析报告', 'w', encoding='utf-8') as f:
        for code in range(len(jj_code)):
            print(f'{jj_name[code]}')
            get_fund_data(jj_code[code])
            print(list_time[0], list_jz[0], gz[0], gz_time[0])
            cha = (gz[0] - list_jz[0]) / list_jz[0] * 100
            print(f'估现差：{cha:.2f}%')
            init_all()


to_cy()
